package com.allm.ai.common.repository;

import com.allm.ai.common.entity.ConversationRound;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;

import java.util.List;
import java.util.Optional;

@Repository
public interface ConversationRoundRepository extends JpaRepository<ConversationRound, Long> {
    
    /**
     * 根据对话ID获取所有轮次，按轮次编号排序
     */
    List<ConversationRound> findByConversationIdOrderByRoundNumberAsc(String conversationId);
    
    /**
     * 根据对话ID获取最新轮次编号
     */
    @Query("SELECT MAX(cr.roundNumber) FROM ConversationRound cr WHERE cr.conversationId = :conversationId")
    Optional<Integer> findMaxRoundNumberByConversationId(@Param("conversationId") String conversationId);
    
    /**
     * 根据对话ID和轮次编号获取轮次
     */
    Optional<ConversationRound> findByConversationIdAndRoundNumber(String conversationId, Integer roundNumber);
    
    /**
     * 统计对话的轮次数量
     */
    long countByConversationId(String conversationId);
    
    /**
     * 根据对话ID删除所有轮次
     */
    void deleteByConversationId(String conversationId);
    
    /**
     * 获取用户的所有对话轮次（用于历史记录）
     */
    @Query("SELECT cr FROM ConversationRound cr WHERE cr.userId = :userId AND cr.isActive = true AND cr.isFirstRound = true ORDER BY cr.lastMessageAt DESC")
    List<ConversationRound> findUserConversationSummaries(@Param("userId") String userId);
    
    /**
     * 根据对话ID获取第一轮（用于摘要）
     */
    @Query(value = "SELECT * FROM conversation_rounds cr WHERE cr.conversation_id = :conversationId AND cr.is_first_round = true LIMIT 1", nativeQuery = true)
    Optional<ConversationRound> findByConversationIdAndIsFirstRoundTrue(@Param("conversationId") String conversationId);
    
    /**
     * 停用对话的所有轮次
     */
    @Modifying
    @Query("UPDATE ConversationRound cr SET cr.isActive = false WHERE cr.conversationId = :conversationId")
    void deactivateByConversationId(@Param("conversationId") String conversationId);

    /**
     * 获取对话的下一个轮次编号
     */
    @Query("SELECT COALESCE(MAX(cr.roundNumber), 0) + 1 FROM ConversationRound cr WHERE cr.conversationId = :conversationId")
    Integer getNextRoundNumber(@Param("conversationId") String conversationId);

    /**
     * 获取用户的所有对话ID（去重）并按时间排序
     */
    @Query("SELECT cr.conversationId, MAX(cr.lastMessageAt) as lastMessageTime " +
           "FROM ConversationRound cr " +
           "WHERE cr.userId = :userId AND cr.isActive = true " +
           "GROUP BY cr.conversationId " +
           "ORDER BY lastMessageTime DESC")
    List<Object[]> findUserConversationIdsWithTime(@Param("userId") String userId);
    
    /**
     * 更新轮次的模型ID列表
     */
    @Modifying
    @Query("UPDATE ConversationRound cr SET cr.modelIds = :modelIds, cr.lastMessageAt = :lastMessageAt WHERE cr.conversationId = :conversationId AND cr.roundNumber = :roundNumber")
    void updateModelIds(@Param("conversationId") String conversationId, 
                       @Param("roundNumber") Integer roundNumber, 
                       @Param("modelIds") String modelIds, 
                       @Param("lastMessageAt") java.time.LocalDateTime lastMessageAt);
}
